#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class InetAddr
{
private:
    void ToHost(const struct sockaddr_in &addr)
    {
        _port = ntohs(addr.sin_port);
        // _ip = inet_ntoa(addr.sin_addr);
        char ip_buf[32];
        ::inet_ntop(AF_INET, &addr.sin_addr, ip_buf, sizeof(ip_buf));
        _ip = ip_buf;
    }

    void IpToHost()
    {
        char ip_buf[32];
        ::inet_ntop(AF_INET, &_addr.sin_addr, ip_buf, sizeof(ip_buf));
        _ip = ip_buf;
    }

    void PortToHost()
    {
        _port = ntohs(_addr.sin_port);
    }

public:
    InetAddr()
    {
    }
    InetAddr(const struct sockaddr_in &addr)
        : _addr(addr)
    {
        ToHost(addr);
    }
    InetAddr(uint16_t port) : _port(port), _ip("")
    {
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    bool operator==(InetAddr &addr)
    {
        return this->_ip == addr._ip && this->_port == addr._port;
    }

    std::string Ip() { return _ip; }

    uint16_t Port() { return _port; }

    struct sockaddr_in addr() { return _addr; }

    struct sockaddr *NetAddr() { return (struct sockaddr *)&_addr; }

    socklen_t NetAddrLen() { return sizeof(_addr); }

    std::string AddrStr() { return _ip + std::to_string(_port); }

    void SetAddr(const sockaddr_in &client, socklen_t &len)
    {
        _addr = client;
        (void)len;

        IpToHost();
    }

    ~InetAddr()
    {
    }

private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _addr;
};